package com.lc.pianostudent.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lc.pianostudent.BaseApplication;
import com.lc.pianostudent.R;
import com.lc.pianostudent.bean.CommentConfig;
import com.lc.pianostudent.bean.CommentsBean;
import com.lc.pianostudent.conn.PostCircleDelect;
import com.lc.pianostudent.conn.PostComment;
import com.lc.pianostudent.conn.PostGetContent;
import com.lc.pianostudent.conn.PostUploadUp;
import com.lc.pianostudent.conn.SendResetPassword;
import com.lc.pianostudent.dialog.DelectDialog;
import com.lc.pianostudent.fragment.FindFragment;
import com.lc.pianostudent.util.KeyboardUtility;
import com.lc.pianostudent.view.CommentListView;
import com.lc.pianostudent.view.SelectPopupWindow;
import com.lc.pianostudent.view.SelectPopupWindowNoPosition;
import com.lc.pianostudent.widget.NineGridLayoutView;
import com.lc.pianostudent.widget.PraiseListView;
import com.zcx.helper.app.AppCallBack;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.glide.GlideLoader;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.R.id.list;

/**
 * Created by Administrator on 2018/7/2.
 */

public class ContactDetailItemActivity extends BaseActivity implements View.OnClickListener{

    @BoundView(R.id.linearlayoutAll) private LinearLayout linearlayoutAll;
    @BoundView(R.id.album_praise_list_layout) private LinearLayout album_praise_list_layout;
    @BoundView(R.id.layout_nine_grid) private NineGridLayoutView layout_nine_grid;
    @BoundView(R.id.praiseListView) private PraiseListView praiseListView;
    @BoundView(R.id.parise_icon) private ImageView parise_icon;
    @BoundView(value = R.id.album_picture,isClick = true)  private CircleImageView album_picture;
    @BoundView(value = R.id.album_user_name_txt,isClick = true) private TextView album_user_name_txt;
    @BoundView(R.id.album_content_txt) private TextView album_content_txt;
    @BoundView(R.id.album_time) private TextView album_time;
    @BoundView(value = R.id.album_praise_layout,isClick = true) private ImageView album_praise_layout;
    @BoundView(R.id.commentList) private CommentListView commentListView;
    @BoundView(value = R.id.linearlayout_comment,isClick = true) private ImageView linearlayoutComment;
    private CommentConfig commentConfig;
    @BoundView(R.id.comment_et)
    private EditText editText;
    @BoundView(R.id.editTextBodyLl)
    private LinearLayout editTextBody;
    @BoundView(value = R.id.comment_send,isClick = true)
    private Button comment_send;
    private  int pinglun_position;
    @BoundView(R.id.bodyLayout) private RelativeLayout bodyLayout;
    private int currentKeyboardH;// 当前软键盘的高度
    private int screenHeight; // 当前屏幕高度
    private int editTextBodyHeight; // 当前输入框的高度
    private PostGetContent.PostGetContentInfo  currentInfo;
    @BoundView(R.id.sanjiao) private ImageView sanjiao;
    @BoundView(R.id.line) private View line;
    private SelectPopupWindow menuWindow;
    private SelectPopupWindowNoPosition selectPopupWindowNoPosition;
    @BoundView(value = R.id.tv_delete,isClick = true) private TextView tv_delete;
    //详细状态
    public PostGetContent postGetContent = new PostGetContent(new AsyCallBack<PostGetContent.PostGetContentInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, final PostGetContent.PostGetContentInfo postGetContentInfo) throws Exception {

            currentInfo = postGetContentInfo;

//            如果是老师
            if(postGetContentInfo.userid.equals(BaseApplication.BasePreferences.readTeacherId())){
                album_user_name_txt.setText(BaseApplication.BasePreferences.readTeacherName().substring(0,1)+"老师");
            }else {
                album_user_name_txt.setText(postGetContentInfo.name);
            }

            GlideLoader.getInstance().get("",postGetContentInfo.avatar,album_picture,R.mipmap.new_head);
            album_time.setText(postGetContentInfo.create_time);
            layout_nine_grid.setUrlList(postGetContentInfo.imgList);

//            Log.e("----s",postGetContentInfo.up+"==jy");
            if(TextUtils.isEmpty(postGetContentInfo.content)){
                album_content_txt.setVisibility(View.GONE);
            }else {
                album_content_txt.setVisibility(View.VISIBLE);
                album_content_txt.setText(postGetContentInfo.content);
            }
//                album_praise_list_layout.setVisibility(View.VISIBLE);
//                praiseListView.setVisibility(View.VISIBLE);
//                parise_icon.setVisibility(View.VISIBLE);
//                praiseListView.setDatas(postGetContentInfo.praiseList);

//            if(postGetContentInfo.listup.equals("true")){
//                linearlayoutAll.setVisibility(View.VISIBLE);
//                commentListView.setVisibility(View.VISIBLE);
//                sanjiao.setVisibility(View.VISIBLE);
//                commentListView.setDatas(postGetContentInfo.commentList);
//            }else {
//                linearlayoutAll.setVisibility(View.GONE);
//                sanjiao.setVisibility(View.GONE);
//            }

            if(postGetContentInfo.up.equals("1")){
                album_praise_layout.setImageResource(R.mipmap.telephone_zan1);
            }else {
                album_praise_layout.setImageResource(R.mipmap.telephone_zan);

            }
            if (postGetContentInfo.listup.equals("true") || postGetContentInfo.upcheck.equals("true")) {
                sanjiao.setVisibility(View.VISIBLE);
                linearlayoutAll.setVisibility(View.VISIBLE);
                //处理点赞列表
                if (postGetContentInfo.upcheck.equals("true")) {
                    if (postGetContentInfo.listup.equals("true")) {
                        line.setVisibility(View.VISIBLE);
                    } else {
                        line.setVisibility(View.GONE);
                    }
//                    Log.e("=====jy",list.get(position).isUpcheck()+"++++");
//                    Log.e("=====jy",list.get(position).getUplist().size()+"++++");
                    album_praise_list_layout.setVisibility(View.VISIBLE);
                    praiseListView.setVisibility(View.VISIBLE);
                    parise_icon.setVisibility(View.VISIBLE);
                    praiseListView.setDatas(postGetContentInfo.praiseList);
                   praiseListView.setOnItemClickListener(new PraiseListView.OnItemClickListener() {
                        @Override
                        public void onClick(int currenr_position) {
                            if( (postGetContentInfo.praiseList.get(currenr_position).getUserid()+"").equals(BaseApplication.BasePreferences.readUID())){
                                context.startActivity(new Intent(context, ContactDetailActivity.class).putExtra("id",(postGetContentInfo.praiseList.get(currenr_position).getUserid()+"")).putExtra("type","0"));
                            }else if((postGetContentInfo.praiseList.get(currenr_position).getUserid()+"").equals(BaseApplication.BasePreferences.readTeacherId())){
                                context.startActivity(new Intent(context, TeacherDetailActivity.class).putExtra("id",(postGetContentInfo.praiseList.get(currenr_position).getUserid()+"")).putExtra("type","1"));

                            }else {
                                context.startActivity(new Intent(context, ContactDetailActivity.class).putExtra("id",(postGetContentInfo.praiseList.get(currenr_position).getUserid()+"")).putExtra("type","1"));

                            }
                        }
                    });
                } else {
                    album_praise_list_layout.setVisibility(View.GONE);
                }
                // 处理评论列表
                if (postGetContentInfo.listup.equals("true")) {
//                    holder.linearlayoutAll.setVisibility(View.VISIBLE);
//                    holder.linearlayoutAll.setVisibility(View.VISIBLE);
                    if (postGetContentInfo.upcheck.equals("true") ) {
                        line.setVisibility(View.VISIBLE);
                    } else {
                        line.setVisibility(View.GONE);
                    }
                    commentListView.setVisibility(View.VISIBLE);

                    commentListView.setDatas(postGetContentInfo.commentList);
                } else {

//                    holder.linearlayoutAll.setVisibility(View.GONE);

                }
            } else {
                linearlayoutAll.setVisibility(View.GONE);
                sanjiao.setVisibility(View.GONE);
            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });
    //点赞接口
    public PostUploadUp postUploadUp = new PostUploadUp(new AsyCallBack<PostUploadUp.PostUploadUpInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostUploadUp.PostUploadUpInfo postUploadUpInfo) throws Exception {
//            UtilToast.show(toast);
            try {
                ((ContactDetailItemActivity.CallBack)getAppCallBack(ContactDetailItemActivity.class)).onRefresh();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });

    //评论接口
    public PostComment postComment = new PostComment(new AsyCallBack<PostComment.PostCommentInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostComment.PostCommentInfo postCommentInfo) throws Exception {
            updateAddComment();
            updateEditTextBodyVisible(View.GONE, null);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });


    //删除状态接口
    public PostCircleDelect postCircleDelect = new PostCircleDelect(new AsyCallBack<PostCircleDelect.PostCircleDelectInfo>(){

        @Override
        public void onSuccess(String toast, int type, Object o, PostCircleDelect.PostCircleDelectInfo postCircleDelectInfo) throws Exception {
            try {
                ((ContactDetailActivity.CallBack)getAppCallBack(ContactDetailActivity.class)).onRefresh();
            } catch (Exception e) {
                e.printStackTrace();
            }

            finish();
        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            UtilToast.show(toast);
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_item);
        setBackTrue();
        setAppCallBack(new CallBack());
        initView();
    }

    private void initView(){
        setTitleName("详情");
        setViewTreeObserver();
        postGetContent.user_id = getIntent().getStringExtra("user_id");
        postGetContent.id = getIntent().getStringExtra("id");
        postGetContent.execute();

        if(BaseApplication.BasePreferences.readUID().equals(getIntent().getStringExtra("user_id"))){
            tv_delete.setVisibility(View.VISIBLE);
        }else {
            tv_delete.setVisibility(View.GONE);
        }
        commentListView.setOnItemClickListener(new CommentListView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                final CommentsBean commentsBean = currentInfo.commentList.get(position);
                if(BaseApplication.BasePreferences.readUID().equals(commentsBean.getUserid())){
                    UtilToast.show("不能回复自己哦~");
                }else {
                    pinglun_position = position;
//                    UtilToast.show("=="+position);
                    CommentConfig config = new CommentConfig();
                    config.commentType = CommentConfig.Type.REPLY;
                    config.commentPosition = position;
                    config.replyUser = currentInfo.commentList.get(position);
                    onItemButtonClick(config);
                }

            }
        });

        layout_nine_grid.setOnItemImageClickListener(new NineGridLayoutView.OnItemImageClickListener() {
            @Override
            public void onItemImageClick(int position, List<String> img) {
//                Log.e("====",position+"==="+img.get(position)+"===");
                menuWindow = new SelectPopupWindow(ContactDetailItemActivity.this,img,position);
                //显示窗口 //设置layout在PopupWindow中显示的位置
                menuWindow.showAtLocation(album_time, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.album_praise_layout:  //点赞
                if(currentInfo.up.equals("2")){
                    postUploadUp.up = "2";

                }else {
                    postUploadUp.up = "1";
                }

                postUploadUp.id = getIntent().getStringExtra("id");
                postUploadUp.user_id = BaseApplication.BasePreferences.readUID();

                postUploadUp.execute();
                break;

            case R.id.linearlayout_comment:  //评论（主评论）
                CommentConfig config = new CommentConfig();
                config.commentType = CommentConfig.Type.PUBLIC;
//                config.replyUser = currentInfo.commentList.get(pinglun_position);
                onItemButtonClick(config);

                break;

            case R.id.comment_send:  //评论发送
                String content = editText.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(ContactDetailItemActivity.this, "评论内容不能为空...", Toast.LENGTH_SHORT).show();
                    return;
                }
//                CommentsBean commentsBean = currentInfo.commentList.get(pinglun_position);
                if(commentConfig.commentType == CommentConfig.Type.PUBLIC){
                    postComment.type = "1";
                    postComment.fromid = "";
                }else if(commentConfig.commentType == CommentConfig.Type.REPLY){
                    postComment.type = "2";
                    postComment.fromid = currentInfo.commentList.get(pinglun_position).getId();
                }

                postComment.id = getIntent().getStringExtra("id");
//                postComment.user_id = BaseApplication.BasePreferences.readUID();
                postComment.user_id = BaseApplication.BasePreferences.readUID();
                postComment.content  = content;
                postComment.execute();

                break;

            case R.id.album_user_name_txt:
                if(getIntent().getStringExtra("user_id").equals(BaseApplication.BasePreferences.readUID())){
                    startActivity(new Intent(context, ContactDetailActivity.class).putExtra("type","0").putExtra("id",getIntent().getStringExtra("user_id")));
                }else if(getIntent().getStringExtra("user_id").equals(BaseApplication.BasePreferences.readTeacherId())){
                    startActivity(new Intent(context, TeacherDetailActivity.class).putExtra("type","1").putExtra("id",getIntent().getStringExtra("user_id")));

                }else {
                    startActivity(new Intent(context, ContactDetailActivity.class).putExtra("type","1").putExtra("id",getIntent().getStringExtra("user_id")));

                }
                break;

            case R.id.album_picture:  //点击看大图
                List<String> headList= new ArrayList<String>();
                headList.add(currentInfo.avatar);
                selectPopupWindowNoPosition = new SelectPopupWindowNoPosition(ContactDetailItemActivity.this,headList,0);
                //显示窗口 //设置layout在PopupWindow中显示的位置
                selectPopupWindowNoPosition.showAtLocation(album_user_name_txt, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;

            case R.id.tv_delete:   // 删除状态
                new DelectDialog(ContactDetailItemActivity.this, R.layout.dialog_delect) {
                    @Override
                    public void cancel() {
                        dismiss();
                    }

                    @Override
                    public void confirm() {

                        postCircleDelect.id = getIntent().getStringExtra("id");
                        postCircleDelect.execute(getContext(),false);

                    }
                }.show();
                break;
        }
    }

    public void updateAddComment() {

        postGetContent.user_id = BaseApplication.BasePreferences.readUID();
        postGetContent.id = getIntent().getStringExtra("id");
        postGetContent.execute(context,false,0);
//        UtilToast.show("12344");
        //清空评论文本
        this.editText.setText("");
    }
    public class CallBack implements AppCallBack {

        public void onRefresh() {
            postGetContent.user_id = BaseApplication.BasePreferences.readUID();
            postGetContent.id = getIntent().getStringExtra("id");
            postGetContent.execute(context,false,0);

        }

    }

    private void onItemButtonClick(CommentConfig config){

        commentConfig = config;
        if (commentConfig.commentType == CommentConfig.Type.REPLY) {
            editText.setHint("回复" + commentConfig.replyUser.getName() + ":");
        }else {
            editText.setHint("说几句吧...");
        }
        this.updateEditTextBodyVisible(View.VISIBLE, commentConfig);
    }

    public void updateEditTextBodyVisible(int visibility, CommentConfig config) {
        this.commentConfig = config;
        this.editTextBody.setVisibility(visibility);
        // 计算偏移量
//        this.measureCircleItemHighAndCommentItemOffset(commentConfig);
        if (View.VISIBLE == visibility) {
            editText.requestFocus();
            //弹出键盘
            KeyboardUtility.showSoftInput(editText.getContext(), editText);
        } else if (View.GONE == visibility) {
            //隐藏键盘
            KeyboardUtility.hideSoftInput(editText.getContext(), editText);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (editTextBody != null && editTextBody.getVisibility() == View.VISIBLE) {
                updateEditTextBodyVisible(View.GONE, null);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    //输入框收回
    private void setViewTreeObserver() {
        bodyLayout = (RelativeLayout) findViewById(R.id.bodyLayout);
        final ViewTreeObserver swipeRefreshLayoutVTO = bodyLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                bodyLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH = getStatusBarHeight();//状态栏高度
                int screenH = bodyLayout.getRootView().getHeight();
                if (r.top != statusBarH) {
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
//                Log.d(TAG, "screenH＝ " + screenH + " &keyboardH = " + keyboardH + " &r.bottom=" + r.bottom + " &top=" + r.top + " &statusBarH=" + statusBarH);

                if (keyboardH == currentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }
                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = editTextBody.getHeight();

                if (keyboardH < 150) {//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE, null);
                    return;
                }

            }
        });
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
